<?php


namespace app\api\controller;
use app\api\model\Order_news;
use app\common\controller\Api;
use think\Db;
use think\Exception;


class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ["*"];

    //用户下单
    public function order_place(){
        $anchor_id = $this->request->post('anchor_id');
        $num = $this->request->post('num',1);
        $user = $this->auth->getUser();

        $anchor = Db::name('user')
            ->where('id',$anchor_id)
            ->where('group_id',1)
            ->where('up_switch',1)
            ->find();
        $anchor_config = Db::name('anchor_config')
            ->where('anchor_id',$anchor_id)
            ->find();
        if(empty($anchor)){
            $this->error('主播不存在或者暂未开播');
        }
        if($num <1 ){
            $this->error("单数不符");
        }
        //判断主播有没有正在进行我的单子
        $order_pro = Db::name('order_place_pro')->where('id',$anchor['order_ing'])->where('user_id',$user['id'])->find();
        if($order_pro){
            $this->error("有自己正在进行中的订单是不能继续下单的");
        }
        $money = round($num * $anchor_config['place_price'],2);
        if($user['money'] < $money){
            $this->error('支付失败,金币不足','',2);
        }

        $order_sn = $this->order_sn();
        $time = time();
        Db::startTrans();
        try {
            //自己在这个主播直播间有没有待服务单子
            $alery_order = Db::name('order_place')->where('status',0)->where('user_id',$user['id'])->where('anchor_id',$anchor_id)->find();
            if($alery_order){
                //续单
                $update = [
                    'num' => $alery_order['num'] + $num,
                    'total_price' => $alery_order['total_price'] + $money,
                    'updatetime' => $time,
                ];
                Db::name('order_place')->where('status',0)->where('user_id',$user['id'])->where('anchor_id',$anchor_id)->update($update);

                $orderdate = [];
                for ($i=1;$i<=$num;$i++){
                    $orderdate[] = [
                        'order_sn'=> $alery_order['order_sn'],
                        'order_id' => $alery_order['id'],
                        'user_id' => $user['id'],
                        'anchor_id'=> $anchor_id,
                        'place_price' => $anchor_config['place_price'],
                        'createtime' => $time,
                        'updatetime' => $time,
                    ];
                }
                //下单
                Db::name('order_place_pro')->insertAll($orderdate);
                //金币消费记录
                \app\common\model\User::money(-$money,$user['id'],1,$alery_order['id'],$num);

            }else{
                $order = [
                    'order_sn'=> $order_sn,
                    'user_id' => $user['id'],
                    'anchor_id'=> $anchor_id,
                    'num' => $num,
                    'place_price' => $anchor_config['place_price'],
                    'total_price' => $money ,
                    'createtime' => $time,
                    'updatetime' => $time,
                ];
                $order_id= Db::name('order_place')->insertGetId($order);

                $orderdate = [];
                for ($i=1;$i<=$num;$i++){
                    $orderdate[] = [
                        'order_sn'=> $order_sn,
                        'order_id' => $order_id,
                        'user_id' => $user['id'],
                        'anchor_id'=> $anchor_id,
                        'place_price' => $anchor_config['place_price'],
                        'createtime' => $time,
                        'updatetime' => $time,
                    ];
                }
                //下单
                Db::name('order_place_pro')->insertAll($orderdate);
                //金币消费记录
                \app\common\model\User::money(-$money,$user['id'],1,$order_id,$num);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }

        $this->success('下单成功',$num);
    }
    function order_sn()
    {
        return date('ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    //主播/用户订单列表
    public function order_list(){
        $status = $this->request->post('status');
        $pagesize = $this->request->post('pagesize',10);
        $user = $this->auth->getUser();
        if($user['group_id'] == 1){ //主播的订单
            if($status == 3){
                $order= Db::name('order_place')
                        ->where('anchor_id',$user['id'])
                        ->order('createtime desc')
                        ->paginate($pagesize)->each(function ($orderdate){
                                $user = $this->auth->getUser();
                                $order_pro = Db::name('order_place_pro')->where('id', $user['order_ing'])->find();
                                if($orderdate['status'] == 1){
                                    $orderdate['custom'] = $order_pro['custom'];
                                }else{
                                    $orderdate['custom'] = '';
                                }
                                $orderdate['createtime'] = date("Y-m-d H:i:s",$orderdate['createtime']);
                                $orderdate['nickname'] = Db::name('user')->where('id',$orderdate['user_id'])->value('nickname');
                                $orderdate['avatar'] = Db::name('user')->where('id',$orderdate['user_id'])->value('avatar');
                                $orderdate['place_or_gen'] = 1;
                                $orderdate['anchor_user'] = Db::name('user')->where('id',$orderdate['anchor_id'])->field('anchor_status,order_ing,board_switch,exit_switch,up_switch')->find();;
                                return $orderdate;
                        });
            }else{
                $order= Db::name('order_place')
                        ->where('status',$status)
                        ->where('anchor_id',$user['id'])
                        ->order('createtime desc')
                        ->paginate($pagesize)->each(function ($orderdate){
                            $user = $this->auth->getUser();
                            $order_pro = Db::name('order_place_pro')->where('id', $user['order_ing'])->find();
                            if($orderdate['status'] == 1){
                                $orderdate['custom'] = $order_pro['custom'];
                            }else{
                                $orderdate['custom'] = '';
                            }
                            $orderdate['place_or_gen'] = 1;
                            $orderdate['createtime'] = date("Y-m-d H:i:s",$orderdate['createtime']);
                            $orderdate['nickname'] = Db::name('user')->where('id',$orderdate['user_id'])->value('nickname');
                            $orderdate['avatar'] = Db::name('user')->where('id',$orderdate['user_id'])->value('avatar');
                            $orderdate['anchor_user'] = Db::name('user')->where('id',$orderdate['anchor_id'])->field('anchor_status,order_ing,board_switch,exit_switch,up_switch')->find();
                            return $orderdate;
                        });
            }
        }elseif ($user['group'] == 0){
            //用户的下单订单
            if($status == 3){
                $order= Db::name('order_place')
                    ->where('user_id',$user['id'])
                    ->order('createtime desc')
                    ->paginate($pagesize)->each(function ($orderdate){
                        $orderdate['createtime'] = date("Y-m-d H:i:s",$orderdate['createtime']);
                        $orderdate['nickname'] = Db::name('user')->where('id',$orderdate['anchor_id'])->value('nickname');
                        $orderdate['avatar'] = Db::name('user')->where('id',$orderdate['anchor_id'])->value('avatar');
                        $orderdate['anchor_user'] = Db::name('user')->where('id',$orderdate['anchor_id'])->field('anchor_status,order_ing,board_switch,exit_switch,up_switch')->find();;
                        $orderdate['place_or_gen'] = 1;
                        return $orderdate;
                    });
            }else{
                $order= Db::name('order_place')
                    ->where('status',$status)
                    ->where('user_id',$user['id'])
                    ->order('createtime desc')
                    ->paginate($pagesize)->each(function ($orderdate){
                        $orderdate['createtime'] = date("Y-m-d H:i:s",$orderdate['createtime']);
                        $orderdate['nickname'] = Db::name('user')->where('id',$orderdate['anchor_id'])->value('nickname');
                        $orderdate['avatar'] = Db::name('user')->where('id',$orderdate['anchor_id'])->value('avatar');
                        $orderdate['anchor_user'] = Db::name('user')->where('id',$orderdate['anchor_id'])->field('anchor_status,order_ing,board_switch,exit_switch,up_switch')->find();
                        $orderdate['place_or_gen'] = 1;
                        return $orderdate;
                    });
            }
            //用户上车的订单
            if($status == 3){
                $gen_order = Db::name('order_gen')->where('user_id',$user['id'])->order('createtime desc')->select();
            }elseif($status == 1){
                $gen_order = Db::name('order_gen')->where('user_id',$user['id'])->where('status',0)->order('createtime desc')->select();
            }elseif($status == 2){
                $gen_order = Db::name('order_gen')->where('user_id',$user['id'])->where('status',1)->order('createtime desc')->select();
            }

            if(!empty($gen_order)){
                //合并排序分页
                foreach ($gen_order as $k=>$v){
                    $gen_order[$k]['createtime'] = date("Y-m-d H:i:s",$v['createtime']);
                    $gen_order[$k]['anchor_user'] = Db::name('user')->where('id',$v['anchor_id'])->field('anchor_status,order_ing,board_switch,exit_switch,up_switch')->find();
                    $gen_order[$k]['place_or_gen'] = 2;
                    $gen_order[$k]['nickname'] = Db::name('user')->where('id',$v['anchor_id'])->value('nickname');
                    $gen_order[$k]['avatar'] = Db::name('user')->where('id',$v['anchor_id'])->value('avatar');
                }
                $pageSize =$pagesize;  //分页每页条数
                $page =  1; //分页页数 默认为1
                $order = $order->toArray();
                $order_merge = array_merge($order['data'],$gen_order);
                $a = $page-1;
                $b = $a * $pageSize;
                //时间排序数组
                $time_array = array();
                foreach ($order_merge as $key => $v) {
                    $time_array[] = $order_merge[$key]['createtime'];
                }
                array_multisort($time_array, SORT_DESC, $order_merge);  //通过时间排序
                $data_rt['total'] = count($order_merge); //获取总条数
                $data_rt['last_page'] = round($data_rt['total'] /$pageSize , 0);
                $order_merge = array_slice($order_merge,$b,$pageSize); //分页部分
                $data_rt['data'] = $order_merge;
//                $rs_arr['data'] = $data_rt;
                $order = $data_rt;
            }
        }
        $this->success('成功',$order);

    }
    //用户上车
    public function order_gen(){
        $order_id = $this->request->post('order_id');
        $anchor_id = $this->request->post('anchor_id');
        $num = $this->request->post('num',1);
        $user = $this->auth->getUser();

        $anchor = Db::name('user')
            ->where('id',$anchor_id)
            ->where('group_id',1)
            ->where('up_switch',1)
            ->find();
        $anchor_config = Db::name('anchor_config')
            ->where('anchor_id',$anchor_id)
            ->find();
        if(empty($anchor)){
            $this->error('主播不存在或者暂未开播');
        }
        if($anchor['board_switch'] == 0){
            $this->error('主播未开启上车功能');
        }
        if($num <1 ){
            $this->error("单数不符");
        }

        $order = Db::name('order_place')->where('id',$order_id)->where('status',1)->find();
        $orderpro = Db::name('order_place_pro')->where('order_id',$order_id)->where('status',1)->find();
        if(!$order || !$orderpro){
            $this->error('此订单有误，请重新进入此页面');
        }
        //        if($order['user_id'] == $user['id']){
//            $this->error('用户不能跟自己下的订单');
//        }


        $myorder_gen = Db::name('order_gen')
            ->where('user_id',$user['id'])
            ->where('orderpro_id',$anchor['order_ing'])
            ->where('status',0)
            ->find();


        $money = round($num * $anchor_config['gen_price'],2);
        if($user['money'] < $money){
            $this->error('支付失败,金币不足','',2);
        }
        $order_sn = $this->order_sn();
        $time = time();
        Db::startTrans();
        try {
            if($myorder_gen){
                //续单子
                $update = [
                    'num' => $myorder_gen['num'] + $num,
                    'remain_num' => $myorder_gen['remain_num'] + $num,
                    'total_price' =>  $myorder_gen['total_price'] + $money,
                    'updatetime'  => time()
                ];
                Db::name('order_gen')
                    ->where('user_id',$user['id'])
                    ->where('orderpro_id',$anchor['order_ing'])
                    ->where('status',0)
                    ->update($update);
                //金币消费记录
                \app\common\model\User::money(-$money,$user['id'],2,$myorder_gen['id'],$num);

            }else{
                //新单子
                $order = [
                    'user_id' => $user['id'],
                    'anchor_id'=> $anchor_id,
                    'order_id' => $order_id,
                    'orderpro_id' => $anchor['order_ing'],
                    'order_sn' => $order_sn,
//                'board_custom' =>$custom,
                    'num' => $num,
                    'remain_num'=>$num,
                    'price' => $anchor_config['gen_price'],
                    'total_price' => $money ,
                    'createtime' => $time,
                    'updatetime' => $time,
                ];
                $order_gen_id= Db::name('order_gen')->insertGetId($order);
                //金币消费记录
                \app\common\model\User::money(-$money,$user['id'],2,$order_gen_id,$num);
            }
//            if($orderpro['custom'] ==1){
//                $custom = 1;
//            }else{
//                $custom = $orderpro['custom'] + 1;
//            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), $e->getTrace());
        }
        $this->success('上车成功');
    }


    //主播的  订单详情
    public function anchor_orderdetail(){
        //下单的订单id
        $id = $this->request->post('id');
        $order_place = Db::name('order_place')->where('id',$id)->find();
        $order_place['user_nickname'] = Db::name('user')->where('id',$order_place['user_id'])->value('nickname');
        $order_place['user_avatar'] = Db::name('user')->where('id',$order_place['user_id'])->value('avatar');
        $order_place['createtime'] = date("Y-m-d H:i:s",$order_place['createtime']);

        //上车用户
        $order_gen = Db::name('order_gen')->where('order_id',$order_place['id'])->select();
        foreach ($order_gen as $k=>$v){
            $order_gen[$k]['createtime'] = date("Y-m-d H:i:s",$v['createtime']);
            $order_gen[$k]['user_nickname'] = Db::name('user')->where('id',$v['user_id'])->value('nickname');
            $order_gen[$k]['user_avatar'] = Db::name('user')->where('id',$v['user_id'])->value('avatar');
        }

        $orderdetail['order_place'] = $order_place;
        $orderdetail['order_gen'] = $order_gen;
        $this->success('成功',$orderdetail);

    }
    //用户的  订单详情
    public function user_orderdetail(){
        //订单id
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if($status ==1){ //下单
            $order = Db::name('order_place')->where('id',$id)->find();
            $order['anchor_nickname'] = Db::name('user')->where('id',$order['anchor_id'])->value('nickname');
            $order['anchor_avatar'] = Db::name('user')->where('id',$order['anchor_id'])->value('avatar');
            $order['createtime'] = date("Y-m-d H:i:s",$order['createtime']);
            $order['price'] = $order['place_price'];
            $this->success('成功',$order);
        }elseif ($status == 2){//上车
            $order = Db::name('order_gen')->where('id',$id)->find();
            $order['anchor_nickname'] = Db::name('user')->where('id',$order['anchor_id'])->value('nickname');
            $order['anchor_avatar'] = Db::name('user')->where('id',$order['anchor_id'])->value('avatar');
            $order['createtime'] = date("Y-m-d H:i:s",$order['createtime']);
            $this->success('成功',$order);
        }

    }

    //订单消息  接口
    public function order_news(){
        $user = $this->auth->getUser();
        $pagesize = $this->request->post('pagesize',10);
        $date = Order_news::where('user_id',$user['id'])
                ->order('createtime desc')
                ->paginate($pagesize)
                ->each(function ($orderdate){
                    $orderdate['createtime'] = date("Y-m-d H:i:s",$orderdate['createtime']);
                    if($orderdate['type'] == 1){
                        $orderdate['types'] = '下单服务';
                        $order = Db::name('order_place')->where('id',$orderdate['order_id'])->find();
                        $orderdate['num'] = $order['num'];
                        $orderdate['price'] = $order['place_price'];
                    }elseif ($orderdate['type'] == 2){
                        $orderdate['types'] = '上车服务';
                        $order = Db::name('order_gen')->where('id',$orderdate['order_id'])->find();
                        $orderdate['num'] = $order['num'];
                        $orderdate['price'] = $order['price'];
                    }elseif ($orderdate['type'] == 3){
                        $orderdate['types'] = '充值服务';
                    }
                    return $orderdate;
                });
        $this->success('成功',$date);
    }
}